package com.strongbj.iot.devices.dam.sub.dacai.request.handle;

import java.io.UnsupportedEncodingException;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import com.strongbj.core.util.ByteUtil;
import com.strongbj.iot.devices.dam.common.AbstractTaskDelayedRunnable;
import com.strongbj.iot.devices.dam.common.DAMManager;
import com.strongbj.iot.devices.dam.common.ITaskManager;
import com.strongbj.iot.devices.dam.message.DAMMessage;
import com.strongbj.iot.devices.dam.message.DAMMessageFactory;
import com.strongbj.iot.devices.dam.response.handle.v1.DAMV1Handle;

import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandlerContext;

public class UpdateDoorStateHandle extends DAMV1Handle {
	private static Logger logger = LogManager.getLogger(UpdateDoorStateHandle.class.getName());
	private static final DAMMessageFactory damMessageFactory = new DAMMessageFactory(); // DAM消息工厂
	/**
	 * 帧头
	 */
	protected final static String COMMAND_HEADER = "EE";
	/**
	 * 帧尾
	 */
	protected final static String COMMAND_FOOTER = "FFFCFFFF";
	protected final static String COMMAND_CODE = "B112";
	
	@Override
	protected boolean isHandleDAMMessage(DAMMessage t) {
		if (t.getCommand() == 0x31) {
			return true;
		} else {
			return false;
		}
	}

	@Override
	public Object handle(ChannelHandlerContext ctx, DAMMessage t) {
		final boolean isOpen = t.getDatas()[0]==0?false:true;  // 0为关门；1为开门
		ITaskManager taskManager = DAMManager.getTaskManager(ByteUtil.byteArrToHexString(t.getAddressCode()));
		taskManager.addSendTask(new AbstractTaskDelayedRunnable() {
			@Override
			protected void taskRun() {
				try {
					sendMessage(ctx, t.getAddressCode(), isOpen);
				} catch (UnsupportedEncodingException e) {
					e.printStackTrace();
				}
			}
		});
		return null;
	}

	private void sendMessage(ChannelHandlerContext ctx, byte[] devAddress,boolean isOpen) throws UnsupportedEncodingException {
		byte[] datas = createDoorMessage(devAddress,isOpen);
		ChannelFuture cf = ctx.channel().writeAndFlush(Unpooled.copiedBuffer(datas));
		cf.addListener(new ChannelFutureListener() {
			@Override
			public void operationComplete(ChannelFuture future) throws Exception {
				if (future.isSuccess()) {
					logger.info("向屏幕下发门状态命令成功 下发命令={}  ", ByteUtil.byteArrToHexString(datas, true));
				} else {
					logger.error("向屏幕下发门状态命令失败 下发命令={}  ", ByteUtil.byteArrToHexString(datas, true));
				}
			}
		});
	}

	private byte[] createDoorMessage(byte[] devAddress,boolean isOpen) throws UnsupportedEncodingException {
		StringBuffer sb = new StringBuffer(COMMAND_HEADER);
		sb.append(COMMAND_CODE);
		sb.append("0001");  // 界面id
		sb.append("000A");  // 控件id
		byte[] datas = (isOpen?"开":"关").getBytes("GBK");
		short dataLen = (short) datas.length;
		sb.append(ByteUtil.byteArrToHexString(ByteUtil.shortToByteArr(dataLen)));  // 控件内容长度
		sb.append(ByteUtil.byteArrToHexString(datas));  // 控件内容
		sb.append(COMMAND_FOOTER);
		
		return damMessageFactory.createDAMMessage(ByteUtil.longToBytes(System.currentTimeMillis()), devAddress, // 设备编号
				(byte) 0, // 设备类型，默认填0
				(byte) 0, // 版本号，默认填0
				(byte) 0xFF, // 设置设备编号命令
				ByteUtil.hexStringToBytes(sb.toString()) // 设置设备编号
		);
	}
}
